<?php

// 微信统一下单
// POST wechat.order

namespace app\api\resource\wechat;
use think\Session;
use app\wechat\lib\Pay;
use app\common\lib\Code;

class Order
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = ['login'];
    // 描述
    public $_description = '微信统一下单';
    // 参数
    public $_param  = [
        'project_id' => '项目主键',
        'title'      => '商品名称,eg:项目评估费',
        'pay_mark'   => '支付标识,cp-初评付款,cx-诚信保证金',
        'code'       => '优惠码,可选',
        'tradeType'  => '支付类型,可选,JSAPI-公众号支付(默认),NATIVE-扫码支付',
    ];
    // 返回
    public $_return = [
        201 => '校验成功',
        400 => '优惠码不可用',
        422 => '项目主键必须',
    ];

    public function run(&$request)
    {
        $projectId = $request->post('project_id/d',0);
        $title     = $request->post('title/s','','trim');
        $openId    = Session::get('member.openid');
        $payMark   = $request->post('pay_mark/s','','trim');
        $code      = $request->post('code/s','','trim');
        $notifyUrl = 'http://jzl.51dojob.com/wechat/pay/callback';
        $tradeType = $request->post('tradeType/s','JSAPI','trim');

        if ( empty($projectId) ) return [422,'项目主键必须'];

        if ( empty($payMark) ) return [422,'支付标识必须'];

        switch ($payMark) {
            case 'cp':
                // $money = 398;
                $money = 0.02;
                break;
            case 'cx':
                // $money = 998;
                $money = 0.01;
                break;
            default:
                $money = 0;
                break;
        }

        if (0 == $money) return [422,'支付标识不合法'];

        // 检查优惠码
        if ( !empty($code) ) {
            if ( !Code::check($code) ) return [400,'优惠码不可用'];
            // $money *= 0.8;
            $money = 0.01;
        }

        $ret = Pay::order($projectId,$payMark,$title,$openId,$money,$notifyUrl,$tradeType,$code);

        return [201,$ret];
    }
}
